package com.lagou.edu.controller;

import com.lagou.edu.model.Token;
import com.lagou.edu.service.CodeFeignClient;
import com.lagou.edu.service.ITokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户控制器
 * @author shenguotao
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private CodeFeignClient codeFeignClient;

    @RequestMapping("/register/{email}/{password}/{code}")
    public int register(@PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code){
        int flag = codeFeignClient.validate(email,code);
        if(flag == 0){//校验成功进行注册操作
            return tokenService.register(email,password,code);
        }
        return flag;
    }

    @RequestMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email){
        return tokenService.isRegistered(email);

    }

    @RequestMapping("/login/{email}/{password}")
    public Token login(@PathVariable("email") String email, @PathVariable("password") String password, HttpServletResponse response){
        Token token = tokenService.login(email,password);
        if(token != null){
            Cookie cookie = new Cookie("token",token.getToken());
            cookie.setHttpOnly(false);
            cookie.setPath("/");
            cookie.setDomain("www.test.com");
            response.addCookie(cookie);
            return token;
        }
        return token;
    }

    @RequestMapping("/info/{token}")
    public String info(@PathVariable("token") String token){
         Token tokeResp = tokenService.findOneByToken(token);
         return tokeResp.getEmail();
    }
}
